<script setup lang="ts">
import type { UploaderAfterRead } from 'vant/lib/uploader/types';
import { ref } from 'vue';
import { updateImage } from '@/services/consult'
import { showLoadingToast } from 'vant';
import type { Image } from '@/types/consult';

defineProps<{
  disabled: boolean
}>()

// 以下代码是把输入的内容提交给父组件
const emit = defineEmits<{
  (e: 'send-text', text: string): void
  (e: 'send-image', img: Image): void
}>()
const text = ref('')
const onSendText = () => {
  emit('send-text', text.value)
  text.value = ''
}

// 实现图片上传把对象传递给父组件
const onAfterRead: UploaderAfterRead = async (item) => {
  if(Array.isArray(item)) return
  if(!item.file) return
  // 上传图片
  const toastLoading = showLoadingToast('正在上传')
  const res = await updateImage(item.file)
  // 关闭缓冲
  toastLoading.close()
  emit('send-image', res.data)
}
</script>

<template>
  <div class="room-action">
    <van-field
      type="text"
      class="input"
      :border="false"
      placeholder="问医生"
      autocomplete="off"
      :disabled="disabled"
      v-model="text"
      @keyup.enter="onSendText"
    ></van-field>
    <!-- :preview-image不预览图片 使用小图标作为上传 -->
    <van-uploader :preview-image="false" :disabled="disabled" :after-read="onAfterRead">
      <cp-icon name="consult-img" />
    </van-uploader>
  </div>
</template>

<style lang="scss" scoped>
.room-action {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 16px;
  z-index: 1;
  box-sizing: border-box;
  .input {
    background-color: var(--cp-bg);
    border: none;
    border-radius: 25px;
    margin-right: 10px;
    padding: 8px 15px;
  }
  .cp-icon {
    width: 24px;
    height: 24px;
  }
}
</style>
